<?php
declare(strict_types=1);

namespace Modules\Production\Http\Controllers;

use Catch\Base\CatchController as Controller;
use App\Services\RedisLockService;
use Modules\Production\Models\ProductionWareOrder;
use Illuminate\Http\Request;
use Modules\Production\Repository\ProductionReportOrderRepository;
use Modules\Production\Repository\productionWareOrderRepository;


class ProductionWareOrderController extends Controller
{
    public function __construct(
        protected readonly ProductionWareOrder $model
    ){}

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        return $this->model->getList();
    }

    /**
     * 箱号查询
     * @param Request $request
     */
    public function lotnum(Request $request){
        $reportInfo = ProductionReportOrderRepository::getReportOrderByLotnum($request->get('lot_num'));
        if(empty($reportInfo)){
            throw new \Exception("当前箱号关联的汇报单已全部入库");
        }

        return ['report' => $reportInfo,'ware' => []];
    }

    /**
     * 数量确认
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        return productionWareOrderRepository::qtyConfirm($request->post());
    }

    /**
     * 生产入库提交
     * @param Request $request
     */
    public function submit(Request $request){

        $postData = $request->post();
        if(!isset($postData['items'][0]['report_id']) || empty($postData['items'][0]['report_id'])){
            throw new \Exception('请求数据有误！');
        }

        $key = 'SCRK_SUBMIT_' . $postData['items'][0]['report_id'];
        $lock = new RedisLockService($key,30);

        if(!$lock->lock()){
            throw new \Exception('当前汇报单入库处理中，请稍后再试');
        }

        try{

            return productionWareOrderRepository::qtySubmit($postData);

        }catch (\Exception $e){
            throw $e;
        } finally {
            $lock->unlock();
        }

    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * 删除生产入库单据
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return productionWareOrderRepository::deleteBy($id);
    }
}
